﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using DevExpress.Web;
using DevExpress.XtraSpreadsheet.Export;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcSensorDataFilterEnglish : System.Web.UI.UserControl
    {
        public string MaSensor { get; set; }
        public int AreaNo { get; set; }

        public int MaDuAn { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["r"] == null || Request.QueryString["n"]==null||Request.QueryString["d"]==null) return;
            var str = Request.QueryString["r"].Split(',');
            var name = Request.QueryString["n"].Split(',');
            int maDa;
            if (!int.TryParse(Request.QueryString["d"], out maDa)) return;
            MaDuAn = maDa;
            if (str.Length <= AreaNo||str.Length!=name.Length)
            {
                return;
            }
            
            MaSensor = str[AreaNo];
            if(!CheckQuyen(MaSensor))return;
            var sensor = (from p in DaoHelper.Entities.Sensors where p.MaSensor==MaSensor select p.MoTa).ToList();
            if(sensor.Count==0) return;
            dataLbl.Text = name[AreaNo]+" - "+(string.IsNullOrEmpty(sensor[0])?"There is no description":sensor[0]);
            var sskey = SessionConst.SES_CHART_DATA + AreaNo;
            if (!IsPostBack)
            {
                Session[sskey] = null;
                if(Session[sskey] == null)
                    Session[sskey] = GetDataDefault();
                grvData.DataSource = Session[sskey];
                grvData.DataBind();
                LoadTestData();
            }
            else {
                if (Session[sskey] != null)
                {
                    grvData.DataSource = Session[sskey];
                }
               // grlDataTest.DataSource = Session[SessionConst.SES_GRL_DATA_TEST + AreaNo];
            }
        }

        protected bool CheckQuyen(string maSesor)
        {
            string user = ((SessionUser) (Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            var e = (from t in DaoHelper.Entities.Sensors
                join b in DaoHelper.Entities.ThietBis on t.MaThietBi equals b.MaThietBi
                join p in DaoHelper.Entities.PhanQuyenDuAns on b.MaDuAn equals p.MaDuAn
                where p.UserName == user
                select p).ToList();
            if (e.Count == 0) return false;
            return true;
        }

        protected void btSearch_Click(object sender, EventArgs e)
        {
          
            Session[SessionConst.SES_CHART_DATA + AreaNo] = GetData();
            LoadGrvData(Session[SessionConst.SES_CHART_DATA + AreaNo]);
        }

        protected void LoadTestData()
        {
           /* grlDataTest.GridView.KeyFieldName = "Id";
            var dt = DaoHelper.Entities.DuLieuTests.Where(p => p.MaSensor == MaSensor).ToList();
            Session[SessionConst.SES_GRL_DATA_TEST+AreaNo] = dt;
            grlDataTest.DataSource = dt;
            grlDataTest.DataBind();*/
            var testData = DaoHelper.Entities.DuLieuTests.FirstOrDefault(
                   p => p.MaSensor == MaSensor && (p.ThoiGianKetThucTest == null || !p.ThoiGianBatDauTest.HasValue));
            if (testData != null && testData.ThoiGianBatDauTest != null)
            {
                deFrom.Date = (DateTime)testData.ThoiGianBatDauTest;
                deFrom.MinDate = (DateTime)testData.ThoiGianBatDauTest;
            }
            else deFrom.Text = string.Empty;

            if (testData != null && testData.ThoiGianKetThucTest != null) 
                deTo.Date = (DateTime)testData.ThoiGianKetThucTest;
            else deTo.Text = string.Empty;

        }

        protected DataTable GetData()
        {
            var rs = (from p in DaoHelper.Entities.Sensors
                      join q in DaoHelper.Entities.SensorValuesTests
                      on p.MaSensor equals q.MaSensor
                      where (p.MaSensor==(MaSensor) && q.MaDuAn==MaDuAn&&
                             (string.IsNullOrEmpty(deFrom.Text) || q.ThoiGianDo >= deFrom.Date)
                             && (string.IsNullOrEmpty(deTo.Text) || q.ThoiGianDo <= deTo.Date))
                      select new
                      {
                          p.MaSensor,
                          p.TenSensor,
                          p.MoTa,
                          q.ThoiGianDo,
                          q.GiaTri,
                      }
                ).OrderByDescending(q => q.ThoiGianDo).ToList();
            var dt = new DataTable();
            dt.Columns.Add("MaSensor");
            dt.Columns.Add("TenSensor");
            dt.Columns.Add("MoTa");
            dt.Columns.Add("ThoiGianDo", typeof(DateTime));
            dt.Columns.Add("GiaTri", typeof(double));
            foreach (var r in rs)
            {
                var dr = dt.NewRow();
                dr["MaSensor"] = r.MaSensor;
                dr["TenSensor"] = r.TenSensor;
                dr["MoTa"] = r.MoTa;
                dr["ThoiGianDo"] = r.ThoiGianDo;
                dr["GiaTri"] = r.GiaTri;
                dt.Rows.Add(dr);
            }
            return dt;
        }

        protected DataTable GetDataDefault()
        {
            var rs= (from p in DaoHelper.Entities.Sensors
                join q in DaoHelper.Entities.SensorValues1000 on p.MaSensor equals q.MaSensor
                     where (p.MaSensor == (MaSensor) && q.MaDuAn == MaDuAn &&
                       (string.IsNullOrEmpty(deFrom.Text ) || q.ThoiGianDo >= deFrom.Date)
                       && (string.IsNullOrEmpty(deTo.Text )  || q.ThoiGianDo <= deTo.Date))
                select new
                {
                    p.MaSensor,
                    p.TenSensor,
                    p.MoTa,
                    q.ThoiGianDo,
                    q.GiaTri
                }
                ).OrderByDescending(q => q.ThoiGianDo).ToList();
            var dt = new DataTable();
            dt.Columns.Add("MaSensor");
            dt.Columns.Add("TenSensor");
            dt.Columns.Add("MoTa");
            dt.Columns.Add("ThoiGianDo",typeof(DateTime));
            dt.Columns.Add("GiaTri", typeof (double));
            foreach (var r in rs)
            {
                var dr = dt.NewRow();
                dr["MaSensor"] = r.MaSensor;
                dr["TenSensor"] = r.TenSensor;
                dr["MoTa"] = r.MoTa;
                dr["ThoiGianDo"] = r.ThoiGianDo;
                dr["GiaTri"] = r.GiaTri;
                dt.Rows.Add(dr);
            }
            return dt;
        }

        protected void btExcel_Click(object sender, EventArgs e)
        {
            gridExport.ExportedRowType = GridViewExportedRowType.All;
            string date = "";
            date += (string.IsNullOrEmpty(deFrom.Text) ? "Từ đầu" : "Từ " + deFrom.Text)+"_";
            date += (string.IsNullOrEmpty(deTo.Text) ? "Đến cuối" : "Đến " + deTo.Text) + "_";
            string name =date+ dataLbl.Text;
            gridExport.WriteXlsxToResponse(name);
            DataTable dt = new DataTable();

        }

        protected void LoadGrvData(object obj)
        {
            grvData.DataSource = obj;
            grvData.DataBind();
        }

        protected void deFrom_DateChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        protected void deTo_DateChanged(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(deTo.Text)) return;
            var date = deTo.Date;
            if (date.Hour == 0 && date.Minute == 0 && date.Second == 0)
                deTo.Date = date.AddHours(23).AddMinutes(59).AddSeconds(59);
        }

        protected void btnSearchHistory_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/DataTransfer/DownloadSensorHistoryData.aspx?r=" + MaSensor+"&p="+ MaDuAn); 
        }

        /*protected void grlDataTest_ValueChanged(object sender, EventArgs e)
        {
            var temp = grlDataTest.GridView.GetRowValuesByKeyValue(grlDataTest.Value, "ThoiGianBatDauTest");
            if (temp != null) deFrom.Date = (DateTime) temp;
            else deFrom.Text = string.Empty;

            temp = grlDataTest.GridView.GetRowValuesByKeyValue(grlDataTest.Value, "ThoiGianKetThucTest");

            if (temp != null) deTo.Date = (DateTime)temp;
            else deTo.Text = string.Empty;

        }*/

    }
}